package com.filyar.htyd.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.filyar.htyd.common.ExceptionEnum;
import com.filyar.htyd.controller.dto.UserDTO;
import com.filyar.htyd.controller.dto.UserPasswordDTO;
import com.filyar.htyd.exception.ServiceException;
import com.filyar.htyd.common.Constants;
import com.filyar.htyd.entity.Menu;
import com.filyar.htyd.entity.User;
import com.filyar.htyd.mapper.RoleMapper;
import com.filyar.htyd.mapper.RoleMenuMapper;
import com.filyar.htyd.mapper.UserMapper;
import com.filyar.htyd.service.IMenuService;
import com.filyar.htyd.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FeiLiYa
 * @since 2022-01-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Log LOG = Log.get();

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String RESTRICTION = "restriction:";
    private static final String RESTRICTED = "restricted:";

    @Override
    public UserDTO login(UserDTO userDTO) {
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(RESTRICTED + userDTO.getUsername()))){
            throw new ServiceException(ExceptionEnum.RESTRICTED_USER.getCode(), "用户："+userDTO.getUsername()+";您已被系统禁止登录！",ExceptionEnum.REGISTER_AUDITING.getNeedToSend());
        }
        Long count = stringRedisTemplate.opsForValue().increment(RESTRICTION + userDTO.getUsername(), 1);
        if ( count != null && count ==1){
            stringRedisTemplate.expire(RESTRICTION + userDTO.getUsername(),5, TimeUnit.MINUTES);
        }else if (count != null && count > 10){
            stringRedisTemplate.opsForValue().set(RESTRICTED+userDTO.getUsername(),"1");
            stringRedisTemplate.delete(RESTRICTION + userDTO.getUsername());
            throw new ServiceException(ExceptionEnum.MALICIOUS_LOGIN_BEHAVIOR.getCode(), "用户："+userDTO.getUsername()+ExceptionEnum.MALICIOUS_LOGIN_BEHAVIOR.getMsg(),ExceptionEnum.MALICIOUS_LOGIN_BEHAVIOR.getNeedToSend());
        }
        User one = getUserInfo(userDTO);
        if (one != null) {
            BeanUtil.copyProperties(one, userDTO, true);

            StpUtil.login(one.getId());
            SaTokenInfo token = StpUtil.getTokenInfo();
            // 设置token
            userDTO.setToken(token.getTokenValue());

            String role = one.getRole(); // ROLE_ADMIN
            // 设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
            userDTO.setMenus(roleMenus);
            StpUtil.getSession().set("user", JSON.toJSONString(one));
            return userDTO;
        } else {
            throw new ServiceException(ExceptionEnum.USERNAME_PASSWORD_ERROR);
        }
    }


    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(ExceptionEnum.OLD_PASSWORD_ERROR);
        }
    }

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误",false);
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Menu> menus = menuService.findMenus("");
        // new一个最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }

    @Override
    public void passwordReset(User user) {
        user.setPassword("Feiliya731!");
        userMapper.updateById(user);
    }

}
